<?php

App::import('Model', 'Expense');
App::import('Model', 'Building');
App::import('Model', 'Installment');
App::import('Model', 'Property');
App::import('Model', 'Account');

class RefinancingPlan extends AppModel {

    var $name = 'RefinancingPlan';
    var $primaryKey = 'refinancing_plan_id';
    //The Associations below have been created with all possible keys, those that are not needed can be removed
    var $belongsTo = array(
        'Person' => array(
            'className' => 'Person',
            'foreignKey' => 'person_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );
    var $hasMany = array(
        'Expense' => array(
            'className' => 'Expense',
            'foreignKey' => 'refinancing_plan_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ),
        'Installment' => array(
            'className' => 'Installment',
            'foreignKey' => 'refinancing_plan_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ),
        'InstallmentMoratorium' => array(
            'className' => 'Installment',
            'foreignKey' => 'moratorium_refinancing_plan_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );

    const NODATA = -1;

    function create_plan($data = null) {
    	
        // Armo un array con datos minimos para testing
//        $data['building_id'] = 5;  // Edificio prevision de gastos
//        $data['person_id'] = 1450; // Tiene todas las propiedades del edificio prevision de gastos
//        $data['expenditure_type_source'] = 5;
//        $data['properties'][0] = 3;
//        $data['properties'][1] = 21;
//        $data['properties'][2] = 39;
//        $data['properties'][3] = 47;
//        $data['properties'][4] = 51;
//        $data['properties'][5] = 59;
//        $data['installment_quantity'] = 12;

        if ($data == null) {
            return NODATA;
        }
        // Tomo el sistema de amortizacion de deudas
        $refinancing_system = Building::getRefinancingSystem($data['building_id']);
		$payment_due        = Building::getPaymentDue($data['building_id']);
		// Inicializacion del plan
        $refinancing_plan_data = array();
        $refinancing_plan_data['RefinancingPlan']['refinancing_plan_id'] = null;
        $refinancing_plan_data['RefinancingPlan']['person_id'] = $data['person_id'];
        $refinancing_plan_data['RefinancingPlan']['expenditure_type_source'] = $data['expenditure_type_source'];
        $refinancing_plan_data['RefinancingPlan']['installment_quantity'] = $data['installment_quantity'];
        $refinancing_plan_data['RefinancingPlan']['amount'] = 0;
        $refinancing_plan_data['RefinancingPlan']['amount_balance'] = 0;
        $refinancing_plan_data['RefinancingPlan']['interest_balance'] = 0;

        // Busqueda de las expensas correspondientes
        $expense = new Expense();
        $expenses = $expense->find('all', array(
                    'fields' => array('Expense.property_id', 'max(Expense.expense_number) as expense_number'),
                    'conditions' => array('Expense.property_id' => $data['properties'],
                                          'Expense.expenditure_type_source' => $data['expenditure_type_source']),
                    'group' => array('Expense.property_id')
                ));
        //var_dump($expenses);
        //calculo del monto a refinanciar
        $i = 0;
        $plan_expense_data = array();
        foreach ($expenses as $expense_included) {
            //var_dump($expense_included);
            $expense_data = $expense->find('first', array(
                        'conditions' => array('Expense.property_id' => $expense_included['Expense']['property_id'],
                                              'Expense.expense_number' => $expense_included[0]['expense_number'],
                                              'Expense.expenditure_type_source' => $data['expenditure_type_source'])
                    ));

            $refinancing_plan_data['RefinancingPlan']['amount'] += $expense_data['Expense']['amount'];
            $refinancing_plan_data['RefinancingPlan']['amount'] += $expense_data['Expense']['interests'];
            $refinancing_plan_data['RefinancingPlan']['amount'] += $expense_data['Expense']['previous_debt'];
            $plan_expense_data[$i] = $expense_data;
            $i++;
        }
        $refinancing_plan_data['RefinancingPlan']['amount_balance'] = $refinancing_plan_data['RefinancingPlan']['amount'];
        // Creacion de la cabecera del plan
        $refinancing_plan = new RefinancingPlan();
        $this->create();
        $this->save($refinancing_plan_data);
        $refinancing_plan_data['RefinancingPlan']['refinancing_plan_id'] = $this->id;
        //var_dump($refinancing_plan_data);

        // Creo las cuotas
        $this->create_plan_installments($refinancing_plan_data, $refinancing_system, $payment_due);
        // Actualizo con el valor de los intereses
        $this->save($refinancing_plan_data);


        //Actualizo el saldo de las cuentas de cada propiedad del plan
        foreach ($data['properties'] as $property_id ) {
            $property = new Property();
            $property_data = $property->read(null,$property_id);
            $account = new Account();
            $account_data = $account->read(null,$property_data['Account']['account_id']);
            $expenditure_type = $expense->getExpenditureTypeSource($data['expenditure_type_source']);
            if ($expenditure_type == "REGULAR") {
                $account_data['Account']['regular_expense_balance'] = 0;
                $account_data['Account']['regular_interests_balance'] = 0;
            } else {
                $account_data['Account']['special_expense_balance'] = 0;
                $account_data['Account']['special_interest_balance'] = 0;
            }
            $account->save($account_data);
        }



        // Cancelo las expensas
        foreach ($plan_expense_data as $expense_data) {
            $expense_data['Expense']['refinancing_plan_id'] = $refinancing_plan_data['RefinancingPlan']['refinancing_plan_id'];
            $expense = new Expense;
            $expense->save($expense_data);
        }
        //die();
    }

    function create_plan_installments( & $refinancing_plan_data, $refinancing_system, $payment_due ){
        $amortization_system = $this->getAmortizationSystemCode($refinancing_system['amortization_system']);
        $annual_rate = $refinancing_system['annual_rate'];
        if ($amortization_system == 'FRENCH')
            $this->create_french_system_installments ($refinancing_plan_data, $annual_rate, $payment_due);
        else
            $this->create_german_system_installments ($refinancing_plan_data, $annual_rate, $payment_due);        
    }

    function create_french_system_installments ( & $refinancing_plan_data, $annual_rate, $payment_due ){
        $interests = 0;
        $monthly_rate = $annual_rate / 12;
        $amount_balance = $refinancing_plan_data['RefinancingPlan']['amount'];
       // $installment_price =  ($refinancing_plan_data['RefinancingPlan']['amount']*$monthly_rate)
         //                      /(pow(1+$monthly_rate,$refinancing_plan_data['RefinancingPlan']['installment_quantity'])-1)
           //                   +$amount_balance * $monthly_rate;
	//modifico el calculo de la couta, yo habia puesto mal la formula en la documentacion (no era al cuadrado era a la n, donde n es el numero de cuotas
	//ahora si deberia dar bien. Miguel
	$numeroCuotas=$refinancing_plan_data['RefinancingPlan']['installment_quantity'];

	$installment_price =  $refinancing_plan_data['RefinancingPlan']['amount']*(pow(1+$monthly_rate,$numeroCuotas)*$monthly_rate)
                               /(pow(1+$monthly_rate,$numeroCuotas)-1);

        for ($i = 1; $i <= $refinancing_plan_data['RefinancingPlan']['installment_quantity']; $i++){
            $installment_data = array();
            $installment_data['Installment']['refinancing_plan_id'] = $refinancing_plan_data['RefinancingPlan']['refinancing_plan_id'];
            $installment_data['Installment']['installment_number'] = $i;
            $installment_data['Installment']['interest'] = round($amount_balance * $monthly_rate,2);
            $installment_data['Installment']['amount'] = round($installment_price - $installment_data['Installment']['interest'],2);
            $installment_data['Installment']['second_due_amount'] = round( $installment_data['Installment']['amount']  * (1 +                      $payment_due['second_due_rate']),2); 
			$installment = new Installment;
            $installment->create();
            $installment->save($installment_data);
            //var_dump($installment_data);
            $amount_balance = $amount_balance - $installment_price + $installment_data['Installment']['interest'];
            $interests += $installment_data['Installment']['interest'];
        }
        $refinancing_plan_data['RefinancingPlan']['interest_balance'] = $interests;
    }

    function create_german_system_installments ( & $refinancing_plan_data, $annual_rate, $payment_due ){
		$interests = 0;
        $monthly_rate = $annual_rate / 12;
        $installment_amount =  $refinancing_plan_data['RefinancingPlan']['amount'] / $refinancing_plan_data['RefinancingPlan']['installment_quantity'];
        $amount_balance = $refinancing_plan_data['RefinancingPlan']['amount'];
        $installment_data = array();
        for ($i = 1; $i <= $refinancing_plan_data['RefinancingPlan']['installment_quantity']; $i++){
            $installment_data['Installment']['refinancing_plan_id'] = $refinancing_plan_data['RefinancingPlan']['refinancing_plan_id'];
            $installment_data['Installment']['installment_number'] = $i;
            $installment_data['Installment']['amount'] = round($installment_amount,2);
            $installment_data['Installment']['interest'] = round($amount_balance * $monthly_rate,2);
            $installment_data['Installment']['second_due_amount'] = round( $installment_data['Installment']['amount']  * (1 +                      $payment_due['second_due_rate']),2); 
            $installment = new Installment;
            $installment->create();
            $installment->save($installment_data);
            $amount_balance -= $installment_amount;
            $interests += $installment_data['Installment']['interest'];
        }
        $refinancing_plan_data['RefinancingPlan']['interest_balance'] = $interests;
    }

    function getAmortizationSystemCode($amortization_system_id) {
        $lookupValue = new LookupValue;
        $lookupValue_data = $lookupValue->read(null, $amortization_system_id);
        return $lookupValue_data["LookupValue"]['lookup_code'];
    }

}

?>
